const taskStatusMap = {
    '60418b08c679e20044c09c0c': '其他功能解决',
    '64af9ca33bb6c5ae1239f98e': '待开发评估',
    '654da2f56c338454318df4de': '待发布SIT(组内环境已测)',
    '5e0dabc57d161c00217800b8': '开发中',
    '6604cf0816117c37565adb54': '待开发',
    '5e0db98a8fc7b60022d301c6': '待组内评审',
    '6535cfab96d44880e05a51b1': '待测试',
    '6535cfab96d44880e05a51b4': '测试中',
    '5f40cf2267d6500044ec1a29': '待分析',
    '6535cfab96d44880e05a51b7': '已发布SIT(合入release部署)',
    '5e0dabc57d161c00217800b9': '已发布生产',
    '60418b08c679e20044c09c0c': '其他功能已解决',
    '614407e924ae43003fd05019': '已完成（不发版）',
    '603ddbf166272e0044b3d934': '已发布UAT',
    '5e0dabc57d161c00217800b7': '待产品内审',
    '5e0db97739a39700233b0199': '待审阅',
    '6340edfabb167700408b7339': '经评估无法实现',
    '65e80e978ec65144610baca1': '待架构组评审'
};
const reviewDeparments = [
    '交付',
    '客户成功部',
    '每刻内部',
    '系统集成部',
    '交付赋能组',
    '云霄事业部',
    '市场中心',
    '费控线-产品市场部',
    '档案线-产品市场部',
    '客户支持和增值服务',
    '售前',
];
const teamList = [
    '风云组',
    '青云组',
    '金砖组',
    '开金组',
    '火舞组',
    '逍遥组',
    '玲珑组',
    '私有云组',
    '项目管理组',
    '交付中心-系统集成部',
    '质量保障组',
    '技术开发组',
    '复杂-跨组',
];

const operationSheetId = Context.argv.sheetId;
const operationRecordId = Context.argv.id;
Application.Record.UpdateRecords({
    SheetId: operationSheetId,
    Records: [{
        id: operationRecordId,
        fields: { '脚本运行日志': '' }
    }]
});
let targetRowData = getTargetRecord(operationSheetId, operationRecordId);
//* [测试代码]-start 
// const operationSheetId = '';
// const operationRecordId = '';
// let targetRowData = { '迭代列表': ['202401-1'], '类型': '迭代统计', '数据表名称': '2024迭代需求' }
//* [测试代码]-end
const executeLoger = Loger();

try {
    main();
} catch (error) {
    Application.Record.UpdateRecords({
        SheetId: operationSheetId,
        Records: [{
            id: operationRecordId,
            fields: { '脚本运行日志': error.toString() }
        }]
    })
}
function main() {
    let interationList = targetRowData['迭代列表'];
    let sheetName = targetRowData['数据表名称'];
    let targetSheet = getSheetByName(sheetName);
    for (let i = 0; i < interationList.length; i++) {
        let interation = interationList[i];
        let data = fetchTaskData(interation);
        mergeSheetData(interation, targetSheet.id, data);
    }
    flagParentTask(targetSheet.id, interationList);
    if (operationSheetId) {
        Application.Record.UpdateRecords({
            SheetId: operationSheetId,
            Records: [{
                id: operationRecordId,
                fields: { '脚本运行日志': `[${dateFormat(new Date())}]:更新成功` }
            }]
        })
    }

}

function convertInteration(v) {
    let list = v.split('-');
    if (list.length == 2) {
        return `${list[0] % 202400}-${list[1]}`
    }
}
function getTargetRecord(sheetId, recordId) {
    let result = Application.Record.GetRecord({ SheetId: sheetId, RecordId: recordId });
    return result.fields;
}
//* 整合sheet的数据，包含增删改操作
function mergeSheetData(interation, sheetId, latestTasks, config = {}) {
    let updateRecords = [];//* 需要更新的sheet数据    
    let latestTaskIds = [];
    let interationSheetTaskIds = [];
    let allSheetTaskIds = [];
    let allParentTaskSourceIds = [];
    let allSheetTaskMap = {};
    let addedRecords = [];
    let sheetData = getSheetData(sheetId);
    let interationSheetData = [];//* sheet中迭代的数据    
    let isStopMerge = false;
    for (let i = 0; i < latestTasks.length; i++) {
        latestTaskIds.push(`DB-${latestTasks[i].uniqueId}`);
    }
    // * 过滤出该迭代的sheet数据
    for (let i = 0; i < sheetData.length; i++) {
        const recordInst = sheetData[i];
        const record = recordInst.fields;
        if (record['迭代'] == interation) {
            interationSheetData.push(recordInst);
            interationSheetTaskIds.push(recordInst.fields['需求编号']);
        }
        allSheetTaskIds.push(recordInst.fields['需求编号']);
        allSheetTaskMap[recordInst.fields['需求编号']] = { id: recordInst.id };
        if (recordInst.fields['parentTaskId']) {
            allParentTaskSourceIds.push(recordInst.fields['parentTaskId']);
        }
    }

    for (let i = 0; i < interationSheetData.length; i++) {
        const recordInst = interationSheetData[i];
        const record = recordInst.fields;
        let taskId = record['需求编号'];
        interationSheetTaskIds.push(taskId);
        if (!latestTaskIds.includes(taskId)) {
            updateRecords.push({ id: recordInst.id, fields: { '迭代': '迭代调整' } });//* 获得迭代中需要移除的任务列表,软删，清楚迭代信息
        }
    }
    for (let i = 0; i < latestTasks.length; i++) {
        let taskId = `DB-${latestTasks[i].uniqueId}`;
        let result = taskCovertSheetRecord(latestTasks[i], interation);
        if (result.code == 'success') {
            if (allSheetTaskIds.includes(taskId)) {
                let sheetTask = allSheetTaskMap[taskId];
                updateRecords.push({ id: sheetTask.id, fields: result.taskRecord });
            } else {
                addedRecords.push({ fields: result.taskRecord });
            }
        } else {
            isStopMerge = true;
        }

    }
    if (isStopMerge) {
        let logData = executeLoger.getLog();
        let text = logData.join('\n');
        if (operationSheetId) {
            Application.Record.UpdateRecords({
                SheetId: operationSheetId,
                Records: [{
                    id: operationRecordId,
                    fields: { '脚本运行日志': text }
                }]
            })
        }
        throw new Error('execute stop');
    }
    //*  更新数据
    if (updateRecords.length > 0) {
        Application.Record.UpdateRecords({
            SheetId: sheetId,
            Records: updateRecords,
        })
    }

    // 创建新的数据
    if (addedRecords.length > 0) {
        console.log(`New data count is ${addedRecords.length}`)
        Application.Record.CreateRecords({
            SheetId: sheetId,
            Records: addedRecords
        });
    }



    // 
    function taskCovertSheetRecord(taskData, interation) {
        let code = 'success';
        const customFields = taskData.customfields;
        const taskRecord = {
            '需求名称': taskData.content, '需求编号': `DB-${taskData.uniqueId}`, '执行者': taskData.executorName,
            '迭代': taskData.sprintName, '需求状态': taskStatusMap[taskData.tfsId] || `未知状态(${taskData.tfsId})`,
            parentTaskId: taskData.parentTaskId, taskId: taskData.id, '发版迭代': genPublishInteration(taskData.sprintName),
        };
        let errorMessage = '';
        for (let i = 0; i < customFields.length; i++) {
            let customField = customFields[i];
            if (customField.value.length > 0) {
                if (customField.cfId == '5f93e91719e65b9393474e07') {
                    taskRecord['负责小组'] = customField.value[0].title == '火舞组' ? '开金组' : customField.value[0].title;
                    if (!teamList.includes(taskRecord['负责小组'])) {
                        errorMessage = `[Error]:负责小组列表未收录，值为【${taskRecord['负责小组']}】,需求编号:${taskRecord['需求编号']}`;
                        console.log(errorMessage);
                        executeLoger.log(errorMessage)
                        code = 'fail';
                    }
                } else if (customField.cfId == '6087706b335ffc1801b386ae') {
                    taskRecord['验收部门'] = customField.value[0].title;
                    if (!reviewDeparments.includes(customField.value[0].title)) {
                        errorMessage = `[Error]:验收部门列表未收录，值为【${customField.value[0].title}】,需求编号:${taskRecord['需求编号']}`;
                        console.log(errorMessage);
                        executeLoger.log(errorMessage)
                        code = 'fail';
                    }
                } else if (customField.cfId == '629f472bcb1bb64c49de8cb1') {
                    taskRecord['驱动因素'] = customField.value[0].title;
                } else if (customField.cfId == '61810ffc967570acea7feabd') {
                    taskRecord['产研人天'] = customField.value[0].title;
                } else if (customField.cfId == '62de3ebad7ab965fbdf6c144') {
                    taskRecord['前端人天'] = customField.value[0].title;
                } else if (customField.cfId == '62de3ed2d51a977b23f42b6b') {
                    taskRecord['后端人天'] = customField.value[0].title;
                } else if (customField.cfId == '62de3ee92d8f775082f164f8') {
                    taskRecord['测试人天'] = customField.value[0].title;
                } else if (customField.cfId == '661e1a022a6cf6625b809aa7') {
                    taskRecord['产品人天'] = customField.value[0].title;
                } else if (customField.cfId == '661e1a366857f29be0e6cbd0') {
                    taskRecord['设计人天'] = customField.value[0].title;
                } else if (customField.cfId == '62de3f13d504e7ffb9ca6787') {
                    taskRecord['实际总人天'] = customField.value[0].title;
                } else if (customField.cfId == '61123175d7d6065f66ee29e7') {
                    taskRecord['主责客户'] = customField.value[0].title;
                } else if (customField.cfId == '660be84c797f388d73107b34') {
                    taskRecord['前端人员'] = customField.value[0].title;
                } else if (customField.cfId == '660be86cfdae364d32426542') {
                    taskRecord['后端人员'] = customField.value[0].title;
                } else if (customField.cfId == '660be8a675863a6977f65356') {
                    taskRecord['测试人员'] = customField.value[0].title;
                }
                // * 特殊处理，架构组人天在202410-1开始，全部汇总在TB中
                let interationMonth = interation.split('-')[0];
                if (Number(interationMonth) >= 202410) {
                    if (customField.cfId == '600e37e3e633856d93e1f21a') {
                        taskRecord['架构组前端评估人天'] = customField.value[0].title;
                    } else if (customField.cfId == '600e3802727d8e77e7e72ee3') {
                        taskRecord['架构组后端评估人天'] = customField.value[0].title;
                    } else if (customField.cfId == '600e3810f38ec6065a90093d') {
                        taskRecord['架构组测试评估人天'] = customField.value[0].title;
                    }
                }
            }
        }
        return { code, taskRecord };
    }

}

function genPublishInteration(interation) {
    let versions = interation.split('-');
    let publishInteration = '';
    if (versions.length >= 2) {
        let year = Number(versions[0].substr(0, 4));
        if (versions[1] == '2') {
            let interationNo = versions[0].substr(4) == '12' ? 1 : Number(versions[0].substr(4)) + 1;
            if (versions[0].substr(4) == '12') {
                year += 1;
            }
            publishInteration = `${year}${interationNo >= 10 ? '' : '0'}${interationNo}`;
        } else {
            publishInteration = versions[0]
        }
    }
    return publishInteration;
}

/* 以下为通用方法,最新代码在lib目录下;受限于wps脚本运行的环境无法使用引用脚本,所以需要手动去更新以下脚本 */

// 获取sheet中的数据
function getSheetData(sheetId) {
    let all = [];
    let offSet = null;
    while (all.length === 0 || offSet) {
        let recordInstance = Application.Record.GetRecords({ SheetId: sheetId, Offset: offSet });
        offSet = recordInstance.offset;
        all = all.concat(recordInstance.records);
    }
    return all;
}

//获取TB迭代的数据
function fetchTaskData(interation) {
    let resp = HTTP.get(`https://quality-tools.maycur.com//teambition_script/sprint/task/?name=${interation}`, {
        timeout: 10000,
    })
    let result = resp.json();
    if (result.code == 'ACK') {
        return result.data;
    } else {
        return [];
    }
}
// 根据数据表名，查找表对象
function getSheetByName(name) {
    let sheets = Application.Sheet.GetSheets();
    let matchedSheet;
    for (let i = 0; i < sheets.length; i++) {
        if (sheets[i].name === name) {
            matchedSheet = sheets[i];
            break;
        }
    }
    if (!matchedSheet) console.warn('The specified table not existed!')
    return matchedSheet;
}
// 日志记录
function Loger() {
    let logList = [];
    let log = (value) => {
        logList.push(value)
    }
    let getLog = () => {
        return logList;
    }
    return { log, getLog };
}
// 替代for表达式
function loop(list, cb) {
    for (let i = 0; i < list.length; i++) {
        cb(list[i], i);
    }
}
// * 标记父需求
function flagParentTask(sheetId, interations) {
    let allTasks = getSheetData(sheetId);
    let updateRecords = [];
    let allParentTaskSourceIds = [];
    loop(allTasks, task => {
        const { fields } = task;
        if (fields['parentTaskId']) {
            allParentTaskSourceIds.push(fields['parentTaskId']);
        }
    })
    if (allParentTaskSourceIds.length > 0) {
        loop(allTasks, task => {
            const { id, fields } = task;
            if (interations.includes(fields['迭代'])) {
                updateRecords.push({ id, fields: { '是否是父任务': allParentTaskSourceIds.includes(fields['taskId']) ? '1' : '0' } })
            }
        })
        if (updateRecords.length > 0) {
            Application.Record.UpdateRecords({
                SheetId: sheetId,
                Records: updateRecords,
            })
        }
    }
}

function dateFormat(date, dateDiveder = "-") {
    function padTwoDigits(num) {
        return num.toString().padStart(2, "0");
    }
    return (
        [
            date.getFullYear(),
            padTwoDigits(date.getMonth() + 1),
            padTwoDigits(date.getDate()),
        ].join(dateDiveder) +
        " " +
        [
            padTwoDigits(date.getHours()),
            padTwoDigits(date.getMinutes()),
            padTwoDigits(date.getSeconds()),
        ].join(":")
    );
}